package me.mononin.dilechat.fragments.purview;


import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import me.mononin.dilechat.LauncherActivity;
import me.mononin.dilechat.R;
import me.mononin.dilechat.activities.MainActivity;
import me.mononin.dilechat.activities.UserActivity;
import me.mononin.dilechat.fragments.media.GalleryFragment;
import me.mononin.factory.persistence.Account;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * @author mononing
 * 权限申请弹出框
 */
public class PermissionFragment extends BottomSheetDialogFragment implements
        EasyPermissions.PermissionCallbacks,View.OnClickListener{

    private static final int RC = 0x0100;
    public PermissionFragment() {
        // Required empty public constructor
    }


    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new BottomSheetDialog(getContext());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_permission, container, false);
        root.findViewById(R.id.btn_submit)
                .setOnClickListener(this);
        return root;
    }


    @Override
    public void onResume() {
        super.onResume();
        //显示界面时刷新
        refreshPermissionStatus(getView());
    }

    /**
     * 刷新应用的权限授予状态
     * @param root 传递的根布局
     */
    private void refreshPermissionStatus(View root){
        if (root==null){
            return;
        }

        Context context = getContext();
        //网络访问权限状态
        root.findViewById(R.id.im_state_permission_network)
                .setVisibility(haveNetworkPermission(context)?View.VISIBLE:View.GONE);
        //读取文件权限状态
        root.findViewById(R.id.im_state_permission_read)
                .setVisibility(haveReadPermission(context)?View.VISIBLE:View.GONE);
        //写入文件权限状态
        root.findViewById(R.id.im_state_permission_write)
                .setVisibility(haveWritePermission(context)?View.VISIBLE:View.GONE);
        //录音权限状态
        root.findViewById(R.id.im_state_permission_record_audio)
                .setVisibility(haveAudioPermission(context)?View.VISIBLE:View.GONE);


        if (haveAllPermWithoutShow(context)){
            // 检查跳转到主页还是登录
            if (Account.isLogin()){
                MainActivity.show(getActivity());
            }else {
                UserActivity.show(getActivity());
            }
            getActivity().finish();
        }
    }

    /**
     * 判断是否拥有网络访问权限
     * @param context 传递上下文
     * @return 返回结果
     */
    private static boolean haveNetworkPermission(Context context){
        String networkPerm[] = new String[]{
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.ACCESS_NETWORK_STATE
        };
        return EasyPermissions.hasPermissions(context,networkPerm);
    }

    /**
     * 判断是否拥有读取文件权限
     * @param context 传递上下文
     * @return 返回结果
     */
    private static boolean haveReadPermission(Context context){
        String readPerm[] = new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE
        };
        return EasyPermissions.hasPermissions(context,readPerm);
    }


    /**
     * 判断是否拥有写入文件权限
     * @param context 传递上下文
     * @return 返回结果
     */
    private static boolean haveWritePermission(Context context){
        String writePerm[] = new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        return EasyPermissions.hasPermissions(context,writePerm);
    }


    /**
     * 判断是否拥有录音权限
     * @param context 传递上下文
     * @return 返回结果
     */
    private static boolean haveAudioPermission(Context context){
        String audioPerm[] = new String[]{
                Manifest.permission.RECORD_AUDIO
        };
        return EasyPermissions.hasPermissions(context,audioPerm);
    }

    public static boolean haveAllPerm(Context context,FragmentManager manager){
        boolean isHaveAll = haveAllPermWithoutShow(context);

        if (!isHaveAll){
            show(manager);
        }

        return isHaveAll;
    }

    public static boolean haveAllPermWithoutShow(Context context){

        return haveNetworkPermission(context)
                &&haveReadPermission(context)
                &&haveWritePermission(context)
                &&haveAudioPermission(context);
    }

    /**
     * 显示权限授权界面
     * @param manager
     */
    private static void show(FragmentManager manager){
        new PermissionFragment()
                .show(manager,PermissionFragment.class.getName());
    }

    @AfterPermissionGranted(RC)
    private void requestAllPerms(){
        String perms[] = new String[]{
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.RECORD_AUDIO
        };

        if (EasyPermissions.hasPermissions(getContext(), perms)) {
            //刷新权限状态
            refreshPermissionStatus(getView());
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, getString(R.string.title_assist_permissions),
                    RC, perms);
        }
    }

    /**
     * 权限申请的时候回调的方法，在这个方法中把对应的权限申请状态交给EasyPermissions框架
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 传递对应的参数，并且告知接收权限的处理者是我自己
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 权限申请成功时回调
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        //当有权限申请失败时，让用户自己跳转到设置界面手动申请权限
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog
                    .Builder(this)
                    .build()
                    .show();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_submit:
                //申请获取全部权限
                requestAllPerms();
                break;
            default:
                break;
        }
    }
}
